package cz.ujep.ki.emap;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class DeliverService extends Service implements ResultListener{
	private JSONQueue queue;
	private static final String prefName = "deliverService_prefs";
	private static final String prefKey = "deliverService_prefs";
	private static final int queueSize = 32;
	
	@Override
	public void onCreate() {
		super.onCreate();
		SharedPreferences prefs = getSharedPreferences(prefName, Context.MODE_PRIVATE);
		String s = prefs.getString(prefKey, "");
		if(s.equals(""))
			queue = new JSONQueue(queueSize);
		else
			queue = new JSONQueue(queueSize, s);
		}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if (intent.hasExtra("message")) { //voláno z aktivity (přidání emoce)
			JSONObject msg;
			try {
				msg = new  JSONObject(intent.getStringExtra("message"));
			} catch (JSONException e1) {
				 return START_STICKY;
			}
			boolean overfilled = queue.push(msg);
			Log.d("Queue", "topo-emotion enqueued");
			if(overfilled)
				Toast.makeText(this, "Too many of topo-emotions. The eldest are lost", 
						Toast.LENGTH_SHORT);
			ConnectivityManager mng = 
					(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo info = mng.getActiveNetworkInfo();
			if (info !=null && info.isConnectedOrConnecting()) 
				startHttpPostThread();
		}
		else {  //voláno z NetworkChangeReciever (pokus o zaslání)
			if(!queue.empty())
				startHttpPostThread();
		}
		return START_STICKY;
	}
	
	
	public void startHttpPostThread() {
		JsonPostTask task = new JsonPostTask(this);
		JSONArray temos = queue.toJSON();
		queue.clear();
		task.execute(temos);
	}
	
	@Override
	public void onDestroy() {
		SharedPreferences prefs = getSharedPreferences(prefName, Context.MODE_PRIVATE);
		Editor edit = prefs.edit();
		edit.putString(prefKey, queue.toJSON().toString());
		edit.commit();
		queue.clear();
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	public void onResult(boolean result) {
		Toast t = Toast.makeText(this, 
				       result ? "Topo-emotions delivered" : "Delivering of topo-emotions failed",
				       Toast.LENGTH_SHORT);
		t.show();
	}

}
